package com.erp.programmer.controller;


import com.erp.programmer.bean.CodeMsg;
import com.erp.programmer.dao.ProductMapper;
import com.erp.programmer.domain.Product;
import com.erp.programmer.dto.PageDto;
import com.erp.programmer.dto.ResponseDto;
import com.erp.programmer.dto.StockOrderDto;
import com.erp.programmer.service.StockOrderService;
import com.erp.programmer.utils.CommonUtil;
import com.erp.programmer.utils.ValidateEntityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author czh
 * @since 2021-05-24
 */
@RestController
@CrossOrigin
@RequestMapping("/stock")
public class StockOrderController {

    @Autowired
    private StockOrderService stockOrderService;

    @Autowired
    private ProductMapper productMapper;

    @PostMapping("/save")
    public ResponseDto<PageDto<StockOrderDto>> save(@RequestBody StockOrderDto stockOrderDto){

        if(stockOrderDto == null){
            return ResponseDto.errorByMsg(CodeMsg.DATA_ERROR);
        }

        CodeMsg validate = ValidateEntityUtil.validate(stockOrderDto);
        if(!validate.getCode().equals(CodeMsg.SUCCESS.getCode())){
            return ResponseDto.errorByMsg(validate);
        }

        if(CommonUtil.isEmpty(stockOrderDto.getProductId())){
            return ResponseDto.errorByMsg(CodeMsg.PRODUCT_NOT_EXIST);
        }
        Product product = productMapper.selectById(stockOrderDto.getProductId());
        if(product == null){
            return ResponseDto.errorByMsg(CodeMsg.PRODUCT_NOT_EXIST);
        }

        if(CommonUtil.isEmpty(stockOrderDto.getId())){
            //添加
            return stockOrderService.add(stockOrderDto);
        }else{
            //修改
            return stockOrderService.edit(stockOrderDto);
        }
    }

    @PostMapping("/delete")
    public ResponseDto<PageDto<StockOrderDto>> delete(@RequestBody StockOrderDto stockOrderDto){

        if(stockOrderDto == null){
            return ResponseDto.errorByMsg(CodeMsg.DATA_ERROR);
        }

        CodeMsg validate = ValidateEntityUtil.validate(stockOrderDto);
        if(!validate.getCode().equals(CodeMsg.SUCCESS.getCode())){
            return ResponseDto.errorByMsg(validate);
        }


        return stockOrderService.delete(stockOrderDto);
    }

    @PostMapping("/get_data")
    public ResponseDto<PageDto<StockOrderDto>> getData(@RequestBody PageDto<StockOrderDto> pageDto){

        return stockOrderService.getData(pageDto);
    }

}

